﻿var controllers = controllers || {};
controllers.school = angular.module('app.Controllers', []);
controllers.school.controller('student', function ($scope, schoolService, $location, $routeParams,$route) {
    $scope.students = [];
    $scope.student = {};
    $scope.loadStudents = function () {
        var url = 'api/Student/GetStudents';
        schoolService.Get(url).success(function (response) {
            $scope.students = response;
        });
    };

    $scope.loadStudent = function (id) {
        if (id > 0) {
            var url = 'api/Student/GetStudent/' + id;
            schoolService.Get(url).success(function (response) {
                $scope.student = response;
            });
        } else {
            $scope.newStudent();
        }
    };

    $scope.newStudent = function () {
        $scope.student = { FirstName: '', MidName: '', LastName: '' };
    },

    $scope.saveStudent = function () {
        var id = $routeParams.id,
            url = id > 0 ? 'api/Student/Update':'api/Student/Add',
            data = $scope.student;
        schoolService.Post(url, data).
            then(function () {
                $location.path("/Students");
                $scope.student = [];
        });
        //console.log($routeParams.id);
        //console.log($route);
        //var url = 'api/Student/Update',
        //    data = $scope.student;
        //schoolService.Post(url, data).
        //    then(function () {
        //        $location.path("/Students");
        //        $scope.student = [];
        //});
    };

    $scope.removeStudent = function (id) {
        var url = 'api/Student/Remove/' + id;
        schoolService.Post(url, null).
            then(function () {
                //$location.path("/Students");
                //$scope.student = [];
                $scope.loadStudents();
            });
    },
    //$scope.editStudent = function ($scope) {
    //    console.log($scope);
    //    $location.path("/#/Student/" + $scope.Id);
    //},

    $scope.cancel = function () {
        $location.path("/Students");
    };
    
    $scope.$on('$routeChangeSuccess', function (scope, next, current) {
        if (typeof next.params.id != "undefined")
            $scope.loadStudent(next.params.id);
        else {
            $scope.loadStudents();
        }
    });
});